package com.etc.controller;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.etc.entity.User;
import com.etc.service.UserService;
import com.etc.util.AbsResponseData;
import com.etc.util.MyJWTHutool;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "管理的接口", description = "处理用户操作的后端接口")
public class UserController {

	Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService service;

	@Autowired
	private RedisTemplate redisTemplate;

	@PostMapping("user/login")
	@ApiOperation(value = "登录", httpMethod = "POST", notes = "登录", response = AbsResponseData.class)
	public AbsResponseData<User> login(@RequestBody User user) {
		// 拿到验证码
		String vcode = user.getVcode();

		// 调用业务代码去查询
		// redisTemplate =>得到所有captcha开头的key
		Set<String> set = redisTemplate.keys("captcha*");
		boolean flag = false;
		
		logger.info("login :"+user);
		//
		for (String k : set) {
			String v = redisTemplate.opsForValue().get(k) + "";
			if (v.equals(vcode)) {
				flag = true;
				break;
			}
		}

		AbsResponseData ard = new AbsResponseData();

		logger.info("vcode是否验证通过: " + flag);
//		如果验证码验证失败，直接返回信息给login.html
		if (!flag) {
			ard.setMsg("vcode_error");
			return ard;
		}
		// 去调用业务代码完成登录的业务
		User u = service.login(user);
		//验证通过
		if (u != null) {
			ard.setMsg("success");
			ard.setObj(u);
			
			// 成成一个jwt token ,将token的数据以json形式返回给客户端
			String token = MyJWTHutool.createToken(u.getId(), u.getLoginname());
			ard.setToken(token);

			
		}
		else {
			ard.setMsg("login_error");
		}
		return ard;
	}
}
